<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center">
                        <div v-if="!route.query.id">新增物料盘点单</div>
                        <div v-else>
                            <span class="text-sm mr-2" style="color: var(--el-text-color-regular)">
                                物料盘点单盘点单编码:
                            </span>
                            <el-tag>{{ route.query.code }}</el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div class="flex items-center" v-if="Boolean(!route.query.readonly)">
                        <el-button type="primary" @click="submitForm">保 存</el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form :model="form" :rules="rules" :disabled="Boolean(route.query.readonly)"
                            ref="materialReceiptRef" label-width="100px">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="盘点日期" prop="inventoryDate">
                                        <el-date-picker style="width: 100%" v-model="form.inventoryDate" type="datetime"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="盘点仓库" prop="store">
                                        <el-input v-model="form.store" style="width: 100%" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="盘点月份" prop="inventoryMonth">
                                        <el-date-picker style="width: 100%" v-model="form.inventoryMonth" clearable
                                            type="month" value-format="YYYY-MM" placeholder="请选择盘点月份" />
                                    </el-form-item>
                                </el-col>

                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="盘点人" prop="createBy">
                                        <el-input v-model="form.createBy" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="创建人" prop="createBy">
                                        <el-input v-model="form.createBy" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="创建时间" prop="createTime">
                                        <el-date-picker style="width: 100%" v-model="form.createTime" type="datetime"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
                <el-collapse-item disabled  title="盘点明细" name="2">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">盘点明细</span>
                    </template>
                    <el-button style="margin-bottom: 10px;" type="primary" size="small" @click="handleMateriel"
                        :disabled="Boolean(route.query.readonly)">从入库单选择</el-button>
                    <el-table v-loading="loading" class="table-form" :data="mesMaterialInventorydetailList"
                        :header-cell-class-name="must">
                        <el-table-column label="序号" width="60" type="index" align="center" :header-cell-class-name="must">
                        </el-table-column>
                        <el-table-column label="入库单编码" min-width="120" align="center" prop="inCode"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="物料分类" min-width="150" align="center" prop="className"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="物料编码" min-width="150" align="center" prop="materialCode"
                            :show-overflow-tooltip="true">

                        </el-table-column>
                        <el-table-column label="物料名称" min-width="150" align="center" prop="materialName"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="规格型号" min-width="120" align="center" prop="specs"
                            :show-overflow-tooltip="true">
<!--                            <template #default="scope">-->
<!--                                <dict-tag :options="mes_paper_specs" :value="scope.row.specs" />-->
<!--                            </template>-->
                        </el-table-column>
                        <el-table-column label="单位" min-width="120" align="center" prop="unit"
                            :show-overflow-tooltip="true">
                            <template #default="scope">
                                <dict-tag :options="mes_material_unit" :value="scope.row.unit" />
                            </template>
                        </el-table-column>
                        <el-table-column label="库存数量" prop="storeQuantity" align="center" width="130">

                        </el-table-column>
                        <!-- <el-table-column label="上次库存" prop="indetailQuantity" align="center" width="130">
                            <template #default="scope">
                                <el-input v-model="scope.row.quantity" :disabled="Boolean(route.query.readonly)"
                                    type="number" />
                            </template>
                        </el-table-column> -->
                        <el-table-column label="库存金额" prop="storeAmount" disabled align="center" width="120">
                        </el-table-column>
                        <el-table-column label="盘点数量" prop="inventoryQuantity" disabled align="center" width="120">
                            <template #default="scope">
                                <el-input v-model="scope.row.inventoryQuantity" :disabled="Boolean(route.query.readonly)"
                                    type="number" @change="changeNumber(scope.row)" placeholder="请填写" />
                            </template>
                        </el-table-column>
                        <el-table-column label="盘点金额" prop="inventoryAmount" align="center" width="120">
                        </el-table-column>
                        <el-table-column label="盘盈盘亏(数量)" prop="ykQuantity" disabled align="center" width="120">
                            <template #default="scope">
                                <el-input v-model="scope.row.ykQuantity" :disabled="Boolean(route.query.readonly)"
                                    type="number" @change="changeYkAmount(scope.row)" placeholder="请填写" />
                            </template>
                        </el-table-column>
                        <el-table-column label="盘盈盘亏(金额)" prop="ykAmount" align="center" width="120">
                        </el-table-column>
                        <el-table-column label="差额原因" prop="differenceReason" disabled align="center" width="120">
                            <template #default="scope">
                                <el-input v-model="scope.row.differenceReason" :disabled="Boolean(route.query.readonly)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-tooltip content="删除" placement="top">
                                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                                        :disabled="Boolean(route.query.readonly)"></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-collapse-item>
            </el-collapse>
        </el-card>


        <!-- 从入库单选择 -->
        <searchMaterialReceipt :visible="searchMaterialReceiptVisible" @changeUpdate="changeSearchMaterialReceipt"
            @cancel="() => { searchMaterialReceiptVisible = false }"></searchMaterialReceipt>
    </div>
</template>
<script setup>
import { getMaterialinventory, updateMaterialinventory, addMaterialinventory } from '@/api/storage/MaterialInventorySheet.js'


import searchMaterialReceipt from './searchMaterialReceipt.vue'
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
const tagsViewStore = useTagsViewStore()
const { proxy } = getCurrentInstance();
const { mes_material_unit, mes_paper_specs } = proxy.useDict('mes_material_unit', 'mes_paper_specs');
const route = useRoute()
const router = useRouter()
const activeNames = ['1', '2']
const materialReceiptRef = ref(null)
const searchMaterialReceiptVisible = ref(false)
const loading = ref(false)
const userInfo = useUserStore()
const mesMaterialInventorydetailList = ref([])



const data = reactive({
    form: {
    },
    rules: {
        inventoryDate: [{ required: true, message: "盘点日期不能为空", trigger: "change" },],
        inventoryMonth: [{ required: true, message: "盘点月份不能为空", trigger: ["blur", "change"] }],
        createBy: [{ required: true, message: "创建人不能为空", trigger: ["change"] }],
        createTime: [{ required: true, message: "创建时间不能为空", trigger: ["change"] }],
    }
});
const { form, rules } = toRefs(data);
if (route.query.id) {
    getMaterialinventory(route.query.id).then(response => {
        form.value = response.data
        mesMaterialInventorydetailList.value = response.data.mesMaterialInventorydetailList
    })

} else {
    form.value = {}
    form.value.store = '物料库'
    form.value.createBy = userInfo.name

}
// 获取当前时间
const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    form.value.inventoryDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
getCurrentDateTime()



const changeSearchMaterialReceipt = (row) => {
    console.log('row', row)
    // const rowInfo = { ...row }
    // delete rowInfo.quantity
    // delete rowInfo.amount
    // delete rowInfo.remark
    // rowInfo.materialindetailId = row.id
    // rowInfo.storeQuantity = row.stockNum
    // rowInfo.storeAmount = (Number(row.price) * Number(row.stockNum)).toFixed(2)
    //
    // mesMaterialInventorydetailList.value.push(rowInfo)
    // searchMaterialReceiptVisible.value = false
    //清空之前的选择
    mesMaterialInventorydetailList.value = []
    row.forEach(ele => {
        delete ele.quantity;
        delete ele.amount;
        delete ele.remark
        ele.materialindetailId = ele.id
        ele.storeQuantity = ele.stockNum
        ele.storeAmount = (Number(ele.price) * Number(ele.stockNum)).toFixed(2)
        ele.materialId = ele.materialId
        mesMaterialInventorydetailList.value.push(ele);
    });
    mesMaterialInventorydetailList.value = uniqueByMaterialId(mesMaterialInventorydetailList.value)
    searchMaterialReceiptVisible.value = false;
}
const uniqueByMaterialId = (list) => {
    const seenMaterialIds = {};
    return list.reduce((acc, curr) => {
        if (!seenMaterialIds[curr.id]) {
            seenMaterialIds[curr.id] = true;
            acc.push(curr);
        }
        return acc;
    }, []);
};
//选择入库单
const handleMateriel = () => {
    searchMaterialReceiptVisible.value = true
}
const changeNumber = (row) => {
    row.inventoryAmount = Number((Number(row.inventoryQuantity) * Number(row.price)).toFixed(4))
}
const changeYkAmount = (row) => {
    const ykQuantity = Number(row.ykQuantity);
    const price = Number(row.price);
    row.ykAmount = +(ykQuantity * price).toFixed(4);
}
// 删除
const handleDelete = (row) => {
    proxy.$modal.confirm('是否确认删除该数据？').then(function () {
        mesMaterialInventorydetailList.value = mesMaterialInventorydetailList.value.filter(item => item.id !== row.id)
        proxy.$modal.msgSuccess("删除成功");
    })
}
// 确认
const submitForm = () => {
    const screen = mesMaterialInventorydetailList.value.find(item => {
        return (!item.inventoryQuantity && item.inventoryQuantity !== 0) || (!item.ykQuantity && item.ykQuantity !== 0);
    });
    if (screen) {
        ElMessage({
            message: '请填写盘点明细中的盘点数量字段和盘盈盘亏(数量)',
            type: 'warning',
        })
        return
    }
    materialReceiptRef.value.validate(valid => {
        if (valid) {
            if (route.query.id) {
                updateMaterialinventory({ ...form.value, mesMaterialInventorydetailList: mesMaterialInventorydetailList.value }).then(res => {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    goBack()
                })
            } else {
                addMaterialinventory({ ...form.value, status: 0, mesMaterialInventorydetailList: mesMaterialInventorydetailList.value }).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    goBack()
                })
            }
        }
    });
}

const must = (obj) => {
    let mustColumns = []
    mustColumns = [9, 11];
    if (mustColumns.includes(obj.columnIndex)) {
        return 'must';
    }
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    //router.go(-1)
    if(route.query.moduleCode=="searchMaterialInventorySheet") {
        router.push('/material/searchMaterialInventorySheet')
    }else{
        router.push('/material/MaterialInventorySheet')
    }
    // router.push('/storage/MaterialInventorySheet')
}

</script>

<style lang="scss" scoped>
.footer {
    text-align: center;
}

:deep(.el-pagination) {
    position: unset;
}

.table-form :deep(.el-form-item) {
    margin-bottom: 0;
}

:deep(.el-table th.must div:before) {
    content: '*';
    color: #ff1818;
}
</style>